package cn.yeamin.spring.boot.config;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import com.alibaba.druid.pool.DruidDataSource;

/**
 * @classDesc: 功能描述:(数据源2配置类)
 * @author: 李彤
 * @createTime: 2017年6月29日 上午10:40:46
 * @version: v1.0
 * @copyright:奕明(上海)影视传媒有限公司
 */
@Configuration
@EnableConfigurationProperties(TwoDruidProperties.class)
@EnableTransactionManagement
@MapperScan(basePackages = "cn.yeamin.spring.boot.two.mapper", sqlSessionTemplateRef = "twoSqlSessionTemplate")
public class TwoDataSourceConfig {

	@Bean(name = "twoDataSource")
	public DataSource twoDataSource(TwoDruidProperties druidProperties) {
		DruidDataSource druid = new DruidDataSource();
		druid.setDriverClassName(druidProperties.getDriverClass());
		druid.setUsername(druidProperties.getUsername());
		druid.setPassword(druidProperties.getPassword());
		druid.setUrl(druidProperties.getUrl());
		druid.setMaxActive(druidProperties.getMaxActive());
		druid.setMinIdle(druidProperties.getMinIdle());
		druid.setInitialSize(druidProperties.getInitialSize());
		druid.setTestOnBorrow(druidProperties.isTestOnBorrow());
		return druid;
	}

	@Bean(name = "twoSqlSessionFactory")
	public SqlSessionFactory twoSqlSessionFactory(@Qualifier("twoDataSource") DataSource dataSource) throws Exception {
		SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
		bean.setDataSource(dataSource);
		//bean.setTypeAliasesPackage("cn.yeamin.spring.boot.pojo");
		//bean.setMapperLocations(
		//	new PathMatchingResourcePatternResolver().getResources("classpath:/mybatis/test1/*.xml"));
		return bean.getObject();
	}

	@Bean(name = "twoSqlSessionTemplate")
	public SqlSessionTemplate twoSqlSessionTemplate(
			@Qualifier("twoSqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
		return new SqlSessionTemplate(sqlSessionFactory);
	}

}
